package com.example.shoppingmallspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.shoppingmallspringboot.entity.UniAppUser;
import com.example.shoppingmallspringboot.mapper.UniUserMapper;
import com.example.shoppingmallspringboot.service.UniUserService;
import com.example.shoppingmallspringboot.util.FwResult;
import com.example.shoppingmallspringboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UniUserServiceImpl implements UniUserService {
    
    @Autowired
    private UniUserMapper uniUserMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public FwResult UniLogin(UniAppUser uniAppUser) {
        QueryWrapper<UniAppUser> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", uniAppUser.getOpenId());
        List<UniAppUser> uniAppUserList = uniUserMapper.selectList(wrapper);
        Map<String, String> map = new HashMap<>();
        
        if (uniAppUserList.size() == 0) {
            uniUserMapper.insert(uniAppUser);
            String token = JwtUtil.createToken();
            map.put("token", token);
            map.put("uniId", String.valueOf(uniAppUser.getId()));
            map.put("nickName", uniAppUser.getNickName());
            map.put("avatarUrl", uniAppUser.getAvatarUrl());
        } else {
            String token = JwtUtil.createToken();
            map.put("token", token);
            map.put("uniId", String.valueOf(uniAppUserList.get(0).getId()));
            map.put("nickName", uniAppUserList.get(0).getNickName());
            map.put("avatarUrl", uniAppUserList.get(0).getAvatarUrl());
            redisTemplate.opsForValue().set(token, map, 1440, TimeUnit.MINUTES);
        }
        return FwResult.ok(map);
    }

    @Override
    public FwResult updateAvatarUrl(UniAppUser uniAppUser) {
        UpdateWrapper<UniAppUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", uniAppUser.getId())
                .set("avatar_url", uniAppUser.getAvatarUrl());
        uniUserMapper.update(null, updateWrapper);
        return FwResult.ok();
    }

    @Override
    public FwResult updateNickName(UniAppUser uniAppUser) {
        UpdateWrapper<UniAppUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", uniAppUser.getId())
                .set("nick_name", uniAppUser.getNickName());
        uniUserMapper.update(null, updateWrapper);
        return FwResult.ok();
    }
} 